package niu.toy.spring.mvc.impl.argument;

import cn.hutool.core.convert.Convert;

import niu.toy.spring.ioc.annotation.Nullable;
import niu.toy.spring.mvc.annotation.RequestParam;
import niu.toy.spring.mvc.HandlerArgumentResolver;
import niu.toy.spring.mvc.HandlerMethodParameter;
import niu.toy.spring.mvc.ModelAndViewContainer;
import niu.toy.spring.mvc.NativeWebRequest;


import javax.servlet.http.HttpServletRequest;

public class RequestParamArgumentResolver implements HandlerArgumentResolver {
    @Override
    public boolean supportsParameter(HandlerMethodParameter parameter) {
        if (parameter.hasParameterAnnotation(RequestParam.class)) {
            return true;
        }
        else {
            if (HandlerArgumentResolver.isSimpleProperty(parameter.getParameterType())) {
                return true;
            }
            else {
                return false;
            }
        }
    }

    @Override
    @Nullable
    public final Object resolveArgument(HandlerMethodParameter parameter, NativeWebRequest request, ModelAndViewContainer mavContainer) throws Exception {
        Object arg = getValueByParameterValues(parameter.getParameterName(), parameter, (HttpServletRequest)request.getNativeRequest());
        arg=Convert.convert(parameter.getParameter().getType(),arg);
        return arg;
    }


    @Nullable
    protected Object getValueByParameterValues(String name, HandlerMethodParameter parameter, HttpServletRequest request) throws Exception {
        Object arg = null;
        if (arg == null)
        {
            String[] paramValues = request.getParameterValues(name);
            if (paramValues != null) {
                arg = (paramValues.length == 1 ? paramValues[0] : paramValues);
            }
        }
        return arg;
    }
}
